package com.ldzy.service.impl;

import com.ldzy.mapper.UserMapper;
import com.ldzy.pojo.User;
import com.ldzy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)//注解括号里面是回滚规则，默认只回滚RuntimeException）和程序错误（Error）
    public boolean transfer(User outer, User inner, double money){
        //1.读取数据库中outer的现在余额a,
        Double a = userMapper.getUserByCode(outer.getCode()).getBalance();
        //2.判断a>=money,是否有足够余额来支付
        if (a >= money) {
            //3.如果足够，读取inner余额b
            Double b = userMapper.getUserByCode(inner.getCode()).getBalance();
            //4，修改余额，
            outer.setBalance(a - money);
            inner.setBalance(b + money);
            //5.将新的余额保存到数据库中
            if (userMapper.edit(outer) > 0) {
                if (userMapper.edit(inner) > 0)
                    return true;
                else
                    return false;
            } else {
                return false;
            }
        }
        //如果要求返回失败的信息，告诉调用者，是什么失败原因。可以采用抛出异常，然后使用统一异常来处理这个失败情况
        return false;
    }
}
